package com.ks.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * JDBC工具类，读取数据库配置文件dbconfig.properties获得连接 关闭连接<br />
 * 驼峰命名和下划线之间转换
 * 
 * @author 47475
 *
 */
public class JDBCUtil {

	private static String driverName;
	private static String url;
	private static String user;
	private static String password;
	static {
		try {
			// 加载dbinfo.properties配置文件
			InputStream in = JDBCUtil.class.getClassLoader().getResourceAsStream("dbconfig.properties");
			Properties properties = new Properties();
			properties.load(in);

			// 获取驱动名称、url、用户名以及密码
			driverName = properties.getProperty("DRIVER_NAME");
			url = properties.getProperty("DATABASE_URL");
			user = properties.getProperty("USERNAME");
			password = properties.getProperty("PASSWORD");

			Class.forName(driverName);

		} catch (IOException e) {
			e.printStackTrace();
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 字符串转换成驼峰命名
	 * 
	 * @param str
	 * @return
	 */
	public static String lineToHump(String str) {
		if (str == null || "".equals(str)) {
			return "";
		}
		str = str.toLowerCase();
		Pattern linePattern = Pattern.compile("_(\\w)");
		Matcher matcher = linePattern.matcher(str);
		StringBuffer sb = new StringBuffer();
		while (matcher.find()) {
			matcher.appendReplacement(sb, matcher.group(1).toUpperCase());
		}
		matcher.appendTail(sb);
		return sb.toString();
	}

	/**
	 * 驼峰字符串格式转下划线
	 * 
	 * @param str
	 * @return
	 */
	public static String humpToLine(String str) {

		if (str == null || "".equals(str.trim())) {
			return "";
		}
		int len = str.length();
		StringBuilder sb = new StringBuilder(len);
		for (int i = 0; i < len; i++) {
			char c = str.charAt(i);
			if (Character.isUpperCase(c)) {
				sb.append('_');
				sb.append(Character.toLowerCase(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();

	}

	public static Connection getConnection() throws SQLException {

		return DriverManager.getConnection(url, user, password);

	}

	/**
	 * 关闭PreparedStatement 和 Connection
	 * 
	 * @param ps
	 * @param conn
	 */
	public static void close(PreparedStatement ps, Connection conn) {
		try {
			if (ps != null) {
				ps.close();
			}
			if (conn != null) {
				conn.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 关闭查询结果集ResultSet,如果有的话先关闭这个
	 * 
	 * @param rs
	 */
	public static void closeResultSet(ResultSet rs) {
		try {
			if (rs != null) {
				rs.close();
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

}